package com.cyh.pangu.offer;

public class Offer58 {

//    public String reverseWords(String s) {
//        if (s == null || s.trim().length() == 0) {
//            return s;
//        }
//        s = s.trim();
//        StringBuilder sb = new StringBuilder();
//        char[] chars = s.toCharArray();
//        int len = chars.length;
//
//        int start = chars.length-1, end = chars.length-1;
//        boolean isBank = false;
//        while (start >= 0) {
//            if (chars[start] != ' ') {
//                start--;
//                isBank = false;
//            } else {
//                if (!isBank) {
//                    sb.append(s.substring(start, end+1) + " ");
//                }
//                isBank =  true;
//                start --;
//                end = start;
//
//            }
//        }
//        sb.append(s.substring(start+1, end+1));
//        return sb.toString();
//    }

    public String reverseWords(String s) {
        if (s.equals("")) return s;
        String str = s.trim();
        if (str == null || str.length()==0) {
            return "";
        }
        String[] arr = str.split(" ");
        int length = arr.length;
        StringBuilder builder = new StringBuilder(s.length());
        for(int i=length-1; i>=0; i--) {
            if (!arr[i].equals("") ) {
                builder.append(arr[i]).append(" ");
            }
        }
        return builder.deleteCharAt(builder.length()-1).toString();
    }

    public String reverseWords2(String s) {
        if (s == null || s.trim().length() == 0) {
            return "";
        }
        s = s.trim();
        String[] chars =  s.split(" ");
        StringBuilder sb = new StringBuilder(s.length());
        for (int i = chars.length - 1; i >= 0; i--) {
            if (!chars[i].equals("")) {
                sb.append(chars[i] + " ");
            }
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    public static void main(String[] args) {
        Offer58 offer58 = new Offer58();
        String cc = offer58.reverseWords2(" ");
        System.out.println("cc:" + cc);
    }
}
